<template>
  <div class="avatar_update">
    <img
      class="img_avatar"
      :src="avatar"
      ref="img"
    >
    <div
      class="left"
      @click="$emit('close')"
    >取消</div>
    <div
      class="right"
      @click="onConfirm"
    >确认</div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { setUserPhoto } from '@/api/user'
export default {
  name: 'UpdatePhoto',
  props: {
    avatar: {
      type: [String, Object],
      required: true
    }
  },
  data () {
    return {
      cropper: null
    }
  },
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      // autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false
    })
  },
  methods: {
    onConfirm () {
      this.cropper.getCroppedCanvas().toBlob(blob => {
        this.updateUserPhoto(blob)
      })
    },
    async updateUserPhoto (blob) {
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 持续展示
      })
      const fromData = new FormData()
      fromData.append('photo', blob)
      try {
        const { data } = await setUserPhoto(fromData)
        console.log(data)
        this.$emit('close')
        this.$toast.success('更新成功')
        this.$emit('updatePhoto', data.data.photo)
      } catch (err) {
        console.log(err)
        this.$toast.fail('更新失败')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.avatar_update {
  height: 100%;
  width: 100%;
  background-color: #000;
  .img_avatar {
    display: block;
    max-width: 100%;
  }
  .left,
  .right {
    position: fixed;
    bottom: 0;
    width: 90px;
    height: 90px;
    line-height: 90px;
    text-align: center;
    color: #fff;
    font-size: 26px;
  }
  .left {
    left: 0;
  }
  .right {
    right: 0;
  }
}
</style>
